package demo.xmemcached;

import java.util.ArrayList;
import java.util.List;

import net.rubyeye.xmemcached.MemcachedClient;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Spring 配置实现
 * 
 * @author hemj
 * @date 2016年11月16日
 */
public class XSpringTest {

	public static void main(String[] args) {
		new XSpringTest();
	}

	ApplicationContext context = null;

	XSpringTest() {
		context = new ClassPathXmlApplicationContext("spring-xmemcached.xml");
		List<SetGet> threads1 = new ArrayList<SetGet>();
		for (int i = 0; i < 100; i++) {
			SetGet sg = new SetGet(i);
			threads1.add(sg);
			sg.start();

		}
		for (int i = 0; i < threads1.size(); i++) {
			try {
				threads1.get(i).join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		long start = System.currentTimeMillis();
		List<SetGet> threads = new ArrayList<SetGet>();
		for (int i = 0; i < 100; i++) {
			SetGet sg = new SetGet(i);
			threads.add(sg);
			sg.start();

		}
		for (int i = 0; i < threads.size(); i++) {
			try {
				threads.get(i).join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		long end = System.currentTimeMillis();
		System.out.println("end-start: " + (end - start));
	}

	class SetGet extends Thread {
		int i = 0;

		SetGet(int i) {
			this.i = i;
		}

		public void run() {
			try {
				for (int j = 0; j < 100; j++) {
					MemcachedClient mcc = (MemcachedClient) context.getBean("memcachedClient");
					// 存储数据
					String value = "Free Education" + j;
					mcc.set("runoob" + j, 60, value);
					// 输出值
					System.out
							.println(i + "   " + j + " >> " + value.equals(mcc.get("runoob" + j)));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
